﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using nhCore.db;
using nhLib.Extensions;
using Sunny.UI;
using System.ComponentModel;
using System.Windows.Forms;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace envG;

public partial class Form设备配置 : UIForm
{
    private EnvDbContext _envDbContext = new();

    public Form设备配置()
    {
        InitializeComponent();

        Udgv初始化();
        UsbtnSave.Click += UsbtnSave_Click;

    }

    private void UsbtnSave_Click(object? sender, EventArgs e)
    {
        try
        {
            int ret = _envDbContext.SaveChanges();
            if (ret > 0)
            {
                UIMessageTip.ShowOk($"已更新{ret}条记录。");
            }
            else
            {
                UIMessageTip.ShowWarning($"没有数据更新。");
            }
        }
        catch (Exception ex)
        {
            UIMessageTip.ShowError(ex.Message);
        }
    }

    #region Udgv事件
    private async void Udgv初始化()
    {
        Udgv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //标题居中
        Udgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; //自动列宽
        Udgv.AutoGenerateColumns = false;

        Font font9 = new("宋体", 10.5f);
        //Udgv.ColumnHeadersDefaultCellStyle.Font = font9;
        Udgv.DefaultCellStyle.Font = font9;
        Udgv.RowTemplate.DefaultCellStyle.Font = font9;
        Udgv.NewColumn<DataGridViewTextBoxColumn>(nameof(Station.Name), "站点名称");
        Udgv.NewColumn<DataGridViewTextBoxColumn>(nameof(Station.Id), "Id");
        Udgv.NewColumn<DataGridViewTextBoxColumn>(nameof(Station.HandshakeFrame), "握手帧");
        Udgv.NewColumn<DataGridViewTextBoxColumn>(nameof(Station.Type), "设备类型");

        Udgv.ContextMenuStrip = UiContextMenuStrip站点;
        Udgv.SelectionChanged += Udgv_SelectionChanged;
        Udgv.RowPostPaint += Udgv_RowPostPaint;
        Udgv.CellMouseDown += Udgv_CellMouseDown;
        Udgv.DataError += Udgv_DataError;

        Udgv要素配置.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //标题居中
        Udgv要素配置.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; //自动列宽
        Udgv要素配置.DefaultCellStyle.Font = font9;
        Udgv要素配置.ColumnHeadersDefaultCellStyle.Font = font9;
        Udgv要素配置.RowTemplate.DefaultCellStyle.Font = font9;
        Udgv要素配置.AutoGenerateColumns = false;
        Udgv要素配置.NewColumn<DataGridViewTextBoxColumn>(nameof(ElementConfig.Name), "要素名称");
        Udgv要素配置.NewColumn<DataGridViewTextBoxColumn>(nameof(ElementConfig.Unit), "单位");
        Udgv要素配置.NewColumn<DataGridViewTextBoxColumn>(nameof(ElementConfig.MappingStationId), "映射站点Id");
        Udgv要素配置.NewColumn<DataGridViewTextBoxColumn>(nameof(ElementConfig.StationReg), "站点寄存器");
        Udgv要素配置.NewColumn<DataGridViewTextBoxColumn>(nameof(ElementConfig.DeviceAddress), "传感器地址");
        Udgv要素配置.NewColumn<DataGridViewTextBoxColumn>(nameof(ElementConfig.RegAddress), "寄存器地址");
        Udgv要素配置.NewColumn<DataGridViewTextBoxColumn>(nameof(ElementConfig.FunctionCode), "功能码");
        Udgv要素配置.NewColumn<DataGridViewComboBoxColumn>(nameof(ElementConfig.DataType), "数据类型")
            .DataSource = new List<string>
            {
                NDataType.con_2ByteInt,
                NDataType.con_2ByteUInt,
                NDataType.con_4ByteInt,
                NDataType.con_4ByteFloat,
                NDataType.con_4ByteFloat反序,
            };
        Udgv要素配置.NewColumn<DataGridViewTextBoxColumn>(nameof(ElementConfig.Digits), "小数位");
        Udgv要素配置.NewColumn<DataGridViewComboBoxColumn>(nameof(ElementConfig.Statistics), "统计方式")
            .DataSource = new List<string>
            {
                ElementConfig.con_NOT,
                ElementConfig.con_AVG,
                ElementConfig.con_SUM,
            };
        Udgv要素配置.NewColumn<DataGridViewTextBoxColumn>(nameof(ElementConfig.ElementType), "要素类型");

        Udgv要素配置.ContextMenuStrip = UiContextMenuStrip要素配置;
        Udgv要素配置.RowPostPaint += Udgv_RowPostPaint;
        Udgv要素配置.CellMouseDown += Udgv_CellMouseDown;
        Udgv要素配置.DataError += Udgv_DataError;
        Udgv要素配置.DefaultValuesNeeded += Udgv要素配置_DefaultValuesNeeded;

        Udgv继承要素.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //标题居中
        Udgv继承要素.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; //自动列宽
        Udgv继承要素.DefaultCellStyle.Font = font9;
        Udgv继承要素.ColumnHeadersDefaultCellStyle.Font = font9;
        Udgv继承要素.RowTemplate.DefaultCellStyle.Font = font9;
        Udgv继承要素.AutoGenerateColumns = false;
        Udgv继承要素.ReadOnly = true;
        Udgv继承要素.AllowUserToAddRows = false;
        foreach (DataGridViewColumn col in Udgv要素配置.Columns)
        {
            DataGridViewColumn newCol = new()
            {
                Name = col.Name,
                DataPropertyName = col.DataPropertyName,
                HeaderText = col.HeaderText,
                CellTemplate = col.CellTemplate,
                FillWeight = col.FillWeight,
                Width = col.Width,
                DefaultCellStyle = col.DefaultCellStyle,
            };
            Udgv继承要素.Columns.Add(newCol);
        }

        await _envDbContext.Stations.LoadAsync();

        BindingSource bs = new()
        {
            DataSource = _envDbContext.Stations.Local.ToBindingList(),
        };
        Udgv.DataSource = bs;
        Udgv要素配置.DataSource = bs;
        Udgv要素配置.DataMember = nameof(Station.ElementConfigs);
    }

    private void Udgv要素配置_DefaultValuesNeeded(object? sender, DataGridViewRowEventArgs e)
    {
        if (_envDbContext != null && Udgv.CurrentRow?.DataBoundItem is Station siteDevice)
        {
            e.Row.Cells[nameof(ElementConfig.MappingStationId)].Value = siteDevice.Id; //默认映射到本站点
        }
        e.Row.Cells[nameof(ElementConfig.DataType)].Value = NDataType.con_2ByteInt;
        e.Row.Cells[nameof(ElementConfig.Statistics)].Value = ElementConfig.con_AVG;
    }

    /// <summary>
    /// 加行号
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Udgv_RowPostPaint(object? sender, DataGridViewRowPostPaintEventArgs e)
    {
        DataGridView dgv = (DataGridView)sender!;

        using var brush = new SolidBrush(dgv.RowHeadersDefaultCellStyle.ForeColor);
        e.Graphics.DrawString((
            e.RowIndex + 1).ToString(),
            dgv.DefaultCellStyle.Font,
            brush,
            e.RowBounds.Location.X + 12,
            e.RowBounds.Y + 5);
    }

    private void Udgv_SelectionChanged(object? sender, EventArgs e)
    {
        DataGridView dgv = (DataGridView)sender!;

        if (_envDbContext != null && dgv.CurrentRow?.DataBoundItem is Station station)
        {
            UILabel设备Id.Text = $"{station.Display()}：";
            try
            {
                _envDbContext.Entry(station).Collection(e => e.ElementConfigs).Load();

                //继承
                List<ElementConfig> list = [];
                string handshakeFrame = station.HandshakeFrame;
                int length = handshakeFrame.Length;

                if (length >= 2 &&
                    int.TryParse(
                        handshakeFrame.AsSpan(length - 2),
                        out var serialNumber) &&
                     serialNumber != 0)
                {
                    string frame00 = handshakeFrame.Remove(length - 2) + "00";
                    byte? id00 = _envDbContext.Stations.FirstOrDefault(s => s.HandshakeFrame == frame00)?.Id;
                    list =
                        _envDbContext.ElementConfigs.Where(x => x.StationId == id00).ToList();
                }
                //映射    
                list.AddRange(
                    _envDbContext.ElementConfigs
                        .Where(x => (x.StationId != station.Id) && (x.MappingStationId == station.Id) ).ToList());

                Udgv继承要素.DataSource = list;

            }
            catch (Exception ex)
            {
                UIMessageTip.ShowError(ex.Message);
            }
        }
    }

    /// <summary>
    /// 鼠标右键，选中当前单元格
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Udgv_CellMouseDown(object? sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.RowIndex < 0 || e.ColumnIndex < 0) return;

        if (sender is DataGridView dgv)
        {
            if (e.Button == MouseButtons.Right)
            {
                dgv.ClearSelection();
                dgv.CurrentCell = null;
                dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
                dgv.CurrentCell = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex];
            }
        }
    }
    private void Udgv_DataError(object? sender, DataGridViewDataErrorEventArgs e)
    {
        DataGridView dgv = (DataGridView)sender!;

        UINotifier.Show($"第{e.RowIndex + 1}行‘{dgv.Rows[e.RowIndex].Cells[0].Value}’，‘{dgv.Columns[e.ColumnIndex].HeaderText}’列：" +
            $"{e.Exception?.Message}", UINotifierType.ERROR, "数据错误", false, 3000);
    }

    #endregion

    #region 右键菜单
    private void ToolStripMenuItem要素复制_Click(object sender, EventArgs e)
    {
        if (Udgv要素配置.CurrentRow.DataBoundItem is not ElementConfig elementConfig ||
            Udgv.CurrentRow.DataBoundItem is not Station siteDevice) { return; }

        //var list = _envDbContext.SiteDevices.Local.ToList();
        ElementConfig newElement = (ElementConfig)elementConfig.Clone();
        newElement.Id = 0; //Id是自增加Key,还原为0让EF处理
        newElement.Name += "~复制";

        do
        { //有重复则继续找下一站点寄存器
            newElement.StationReg++;
        } while (siteDevice.ElementConfigs.FirstOrDefault(x => x.StationReg == newElement.StationReg) != default);

        siteDevice.ElementConfigs.Add(newElement);
    }

    private void ToolStripMenuItem站点复制_Click(object sender, EventArgs e)
    {
        if (Udgv.CurrentRow.DataBoundItem is not Station siteDevice) { return; }

        string hf = siteDevice.HandshakeFrame;
        do
        { //有重复则继续找下一握手帧
            hf = IncrementLastTwoDigits(hf);
        } while (_envDbContext.Stations.Local.FirstOrDefault(x => x.HandshakeFrame == hf) != default);

        byte id = siteDevice.Id;
        do
        {
            id++;
        } while (_envDbContext.Stations.Local.FirstOrDefault(x => x.Id == id) != default);

        Station newSite = new()
        {
            Id = id,
            HandshakeFrame = hf,
            Name = siteDevice.Name + "~复制",
            Type = siteDevice.Type,
        };

        _envDbContext.Stations.Add(newSite);

        if (sender is ToolStripMenuItem tsmi && tsmi.Name == nameof(ToolStripMenuItem复制含要素))
        {
            foreach (var ec in siteDevice.ElementConfigs)
            {
                var newElement = (ElementConfig)ec.Clone();
                newElement.StationId = newSite.Id;
                newSite.ElementConfigs.Add(newElement);
            }
        }
    }

    /// <summary>
    /// 字符串后2位加1后返回
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    private static string IncrementLastTwoDigits(string input)
    {
        // 检查输入字符串是否至少有两位数字
        if (input.Length < 2 || !int.TryParse(input.AsSpan(input.Length - 2), out int number))
        {
            return (input);
        }

        number++;
        if (number == 100) { number = 0; }

        // 将结果转换回字符串，并与原字符串结合
        return string.Concat(input.AsSpan(0, input.Length - 2), number.ToString("d2"));
    }
    #endregion
}
